// c库函数头文件
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// 官方标准库头文件
#include "stm32f10x.h"
// 自定义头文件
#include "./LED/led.h"
#include "./BUTTON/button.h"
#include "./BUZZER/buzzer.h"
#include "./BSP/bsp_TiMbase.h"
#include "./BSP/bsp_usart.h"
#include "./BSP/bsp_usart2.h"
#include "./SOFTWARESERIAL/software_serial.h"
#include "./DHT11/dht11.h"
#include "./timer_delays.h"
#include "bit_band.h"
#include "modbus.h"
#include "stm32f10x_rcc.h"
#include "stm32f10x_gpio.h"
#include "./ESP8266/esp8266.h"

// 函数声明
void TASK_CommunicationBetweenMCU(void);
void TASK_HandleCommunicationToPC(void);
void TASK_TestUSART3(void);
void TASK_ESP8266(void);

// 主函数
int main()
{
    // DHT11_DataTypDef dht11_data;
    char msg[128];
    // =========================  初始化外设 ============================
    // LED_Init();             // ³õÊ¼»¯LED¿ØÖÆÒý½Å
    // BUTTON_Init();          // ³õÊ¼»¯°´¼ü¿ØÖÆÒý½Å
    BASIC_TIM_Init(); // ³õÊ¼»¯¶¨Ê±Æ÷7£¬ÓÃÓÚÊµÏÖÊ±¼ä²âÁ¿
    // HCSR04_PinConfg();    // ³õÊ¼»¯³¬Éù²¨¿ØÖÆÒý½Å
    // USART_Config();         //³õÊ¼»¯(ÎïÀí)´®¿Ú1
    // USART2_Config();        //³õÊ¼»¯(ÎïÀí)´®¿Ú2
    //  DHT11_Config();

    SerialPortInit(COM1, 115200);
    SerialPortInit(COM2, 115200);
    ESP8266_Init(); // 初始化ESP8266
    DelayMS(300);
    // ESP8266_BuildTCPConn("IOT_class14", "iot12345678", "192.168.3.99", 777);

    // ======================== ºóÌ¨Ö÷Ñ­»· ==============================
    while (1)
    { // 主循环

        if (usart_get_msg(COM1, msg, sizeof(msg) - 1) > 0)
        {
            usart_clear_msg(COM1);

            printf("****************************************\r\n");

            // ESP8266_SendCMD("AT\r\n", "OK", NULL, 100);
            if (ESP8266_SendCMD(msg, "OK", NULL, 1000))
            {
                printf("\r\n*******************************\r\n\r\n");
            }
        }

#if 0
        if (ESP8266_ConnTest()) {
            printf("conn test ok\r\n");
        }
        
        
        //TASK_ESP8266();
        ESP8266_GetMsg();
        
        if (DHT11_ReadData(&dht11_data)) {
            memset(msg, 0, sizeof(msg));
            sprintf(msg, "%d,%d\r\n", dht11_data.humity[0], dht11_data.temperature[0]);
            ESP8266_SendString(ENABLE, msg);
        }
        
        DelayMS(1000);
        LED_Toggle();   // ¹¤×÷Ö¸Ê¾µÆ
#endif
    }
}
#if 0
/*
测试ESP8266的AT指令
*/
void TASK_ESP8266(void)
{
    char msg[128] = {'\0'}; // Èç¹ûÕ»¿Õ¼ä¹ý´ó£¬ÓÐ¿ÉÄÜÔì³ÉÕ»Òç³ö£¬×¢ÒâÔÚ»ã±à´úÂëÖÐÐÞ¸ÄÕ»¿Õ¼ä´óÐ¡
    char cmd[128] = {'\0'};
    char replay[16] = {'\0'};
    char ms[16] = {'\0'};
    char *val = NULL;

    // step1 Ê¹ÓÃÖÐ¶Ï·½Ê½´Ó´®¿Ú»ñÈ¡Êý¾Ý(ÉÏÎ»»úÖ¸Áî)
    if (usart_get_msg(COM1, msg, sizeof(msg) - 1) > 0)
    {
        usart_clear_msg(COM1);

        printf("******************½ÓÊÕµ½ÉÏÎ»»úÊý¾Ý**********************\r\n");

        printf("msg = |%s|", msg);

        val = strtok(msg, "#");
        if (val != NULL)
        {
            strcpy(cmd, val);
            strcat(cmd, "\r\n");
        }

        val = strtok(NULL, "#");
        if (val != NULL)
        {
            strcpy(replay, val);
        }

        val = strtok(NULL, "#");
        if (val != NULL)
        {
            strcpy(ms, val);
        }

        printf("\r\njson parse ok:|{%s}, {%s}, {%s}|\r\n\r\n", cmd, replay, ms);

        // ESP8266_SendCMD("AT\r\n", "OK", NULL, 100);
        if (ESP8266_SendCMD(cmd, replay, NULL, atoi(ms)))
        {
            printf("\r\n*************ÃüÁî³É¹¦******************\r\n\r\n");
        }
    }
}

/*
短接串口3，测试串口3是否正常工作
*/
void TASK_TestUSART3(void)
{
    u16 len = 0;
    char msg[128] = {'\0'};

    // usart_send_msg(COM3, "i am usart3, who are you?\r\n");
    printf("send to usart3\r\n");
    USART_Puts(USART3, "hello i am usart3\r\n");
    DelayMS(500); // ·¢ËÍ¼ä¸ô500ms

    if ((len = usart_get_msg(COM3, msg, sizeof(msg) - 1)) > 0)
    {

        printf("recv from usart3,len:%d:{%s}", len, msg); // ·¢¸ø´®¿Ú1

        usart_clear_msg(COM3);
        memset(msg, 0, sizeof(msg));
    }
}

/*
     通过串口2，实现两台单片机的通信
*/
void TASK_CommunicationBetweenMCU(void)
{
    u16 len = 0;
    char msg[128] = {'\0'};

    usart_send_msg(COM2, "i am usart2, who are you?\r\n");

    DelayMS(500); // ·¢ËÍ¼ä¸ô500ms

    if ((len = usart_get_msg(COM2, msg, sizeof(msg) - 1)) > 0)
    {

        printf("recv from usart2,len:%d:{%s}", len, msg); // ·¢¸ø´®¿Ú1

        usart_clear_msg(COM2);
        memset(msg, 0, sizeof(msg));
    }
}

/*
单片机与PC间通信,modbus协议，使用uart1
*/
void TASK_HandleCommunicationToPC(void)
{
    char modbus_pack[128] = {'\0'}; // Õ»¿Õ¼ä,¿¼ÂÇ¿Õ¼ä¸´ÓÃ
    char payload[64];

    ModbusTypeDef modbus_obj;
    modbus_obj.payload = payload;
    modbus_obj.payload_size = sizeof(payload);

    // step1 Ê¹ÓÃÖÐ¶Ï·½Ê½´Ó´®¿Ú»ñÈ¡Êý¾Ý(ÉÏÎ»»úÖ¸Áî)
    if (usart_get_msg(COM1, modbus_pack, sizeof(modbus_pack) - 1) > 0)
    {
        usart_clear_msg(COM1);

        printf("modbus frame = %s\r\n", modbus_pack);

        // step2 ½âÎöÉÏÎ»»ú·¢ËÍµÄmodbusÖ¡,µ÷ÊÔÍê³Éºó·â×°½Ó¿Úmodbus_frame_parse()
        bool ret = Modbus_FrameParse(modbus_pack, &modbus_obj);
        if (!ret)
            parse_error_code();

        if (ret)
        {
            // step3 ´¦ÀíÖ¸Áî

            switch (modbus_obj.func_code)
            {
            case 1: // ´ò¿ªLED
                LED_SetState(LED_GREEN, LED_ON);
                break;
            case 2: // ¹Ø±Õ
                LED_SetState(LED_GREEN, LED_OFF);
                break;
            }
        }
        // step4 Çå¿Õ»º³åÇø
        memset(modbus_pack, 0, sizeof(modbus_pack));

        // step5 »ØÓ¦modbusÖ¡, ·â×°modbus_frame_pack();
        modbus_obj.slave_addr = 3;
        modbus_obj.func_code = 5;
        strcpy(modbus_obj.payload, "15x");
        modbus_obj.len = strlen(modbus_obj.payload);
        Modbus_FramePack(&modbus_obj, modbus_pack);

        usart_send_msg(COM1, modbus_pack);
    }
}
#endif
